package com.atguigu.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {
    public static void main(String[] args) throws Exception {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7001));
        String filename = "protoc-3.6.1-win32.zip";

        //得到一个文件channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();

        //准备发送
        long startTime = System.currentTimeMillis();

        //在linux下一个transferTo 方法就可以完成传输
        //在windows 下 一次调用 transferTo 只能发送8m , 就需要分段传输文件, 而且要主要
        //传输时的位置 =》 课后思考...
        //transferTo 底层使用到零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

        System.out.println("发送的总的字节数 =" + transferCount + " 耗时:" + (System.currentTimeMillis() - startTime));

        //关闭
        fileChannel.close();

    }

    public static void sendBigFile() throws IOException {

        SocketChannel socketChannel = SocketChannel.open();

        socketChannel.connect(new InetSocketAddress("127.0.0.1",7001));
        String filename = "protoc-3.6.1-win32.zip";

        FileChannel fileChannel = new FileInputStream(filename).getChannel();
        //准备发送大文件

        long position = 0;
        long size = fileChannel.size();
        long total = 0;
        long startTime = System.currentTimeMillis();
        while (position < size) {
            long transfer = fileChannel.transferTo(position, fileChannel.size(), socketChannel);
            System.out.println("本次发送：" + transfer);
            if (transfer <= 0) {
                break;
            }
            total += transfer;
            position += transfer;
        }
        System.out.println("发送的总的字节数 =" + total + " 耗时:" + (System.currentTimeMillis() - startTime));
        fileChannel.close();

    }
}
